#include "global.h"
#include <math.h>

#define ADC_BUFFER_LENGHT 20

bank3 volatile unsigned int QSUM=0;
bank3 volatile unsigned int ADCBuffer[ADC_BUFFER_LENGHT];
bank3 volatile unsigned int AvLine, MaxValue, Amplitude, MinValue,TempN;


bank3 unsigned char ADCpointer;  // point to lastest stored value

union 
{
	unsigned int INT;
	unsigned char BYTE[2];
	struct
	{	unsigned char Low;
		unsigned char High;
	}Byte;
}Convert;


void ADC2Buffer(void)
{
	if((ADCpointer+=1) == ADC_BUFFER_LENGHT) ADCpointer=0;
		Convert.BYTE[0]=ADRESL;
		Convert.BYTE[1]=ADRESH;
		ADCBuffer[ADCpointer]=Convert.INT;
}

void ADC2Temp(void)
{
	Convert.BYTE[0]=ADRESL;
	Convert.BYTE[1]=ADRESH;
	TempN=Convert.INT;
};
//====================================================================
void ADC_CurrentService(void)
{ 
	unsigned int temp=0;
	unsigned char i;
	static unsigned int CA,CB;
	QSUM=0;
	ADIF=0;
	for (i=0; i<ADC_BUFFER_LENGHT; i++)
	{	temp=ADCBuffer[i];
		QSUM+=temp;
	}
	AvLine = QSUM/ADC_BUFFER_LENGHT;
		QSUM =0;
	MinValue = AvLine;
	MaxValue = AvLine;
/*	for (i=0; i<ADC_BUFFER_LENGHT; i++)
	{	temp=ADCBuffer[i];
		if (temp>AvLine)
		{
			temp = temp-AvLine;
		}else
		{
			temp = AvLine - temp;
		};
		QSUM+=temp*temp;
	}
	temp = (unsigned int)sqrt(QSUM);
*/
for (i=0; i<ADC_BUFFER_LENGHT; i++)
	{	temp=ADCBuffer[i];
		if (temp>MaxValue)
		{
			MaxValue = temp;
		};
		if(temp< MinValue)
		{
			MinValue = temp;
		};
	}
	
	temp = (MaxValue - MinValue)*10;
	if (temp !=0) 
	{
		temp /= 3;
	};
//================================================================
//
//		MEDIAN OUTPUT
//
//================================================================
	if (CA >= CB) 
	{
		if (temp>=CB) // CA>CB  CT>CB  - CB smollest one
		{
			if (CA>=temp)
			{
				Amplitude =  temp;
			}
			else
			{
 				Amplitude = CA;
			};
		}
		else //  CA>CB   CB>CT
		{
			Amplitude=CB;
		};
	} 
	else	// CA<CB
	{
		if (temp >= CB) // CA<CB  CB <= CT  		
		{
			Amplitude = CB;
		}
		else // CA< CB  CT <= CB  - CB highest
		{
			if (CA>=temp)
			{	
				Amplitude = CA;
			}
			else 
			{
				Amplitude = temp;
			};
		};
	}
	CA = CB;
	CB = temp;



	ADIF=1;
};






//====================================================================
void SelectADCSource(unsigned char source)
{ 
	unsigned char i;
	ADCON0&=0b11000111;
	source=(source<<3);
	source&=0x38;
	ADCON0|=source;

};
//====================================================================
unsigned int ADCTemp(void)
{
	return TempN;
};

//====================================================================
unsigned int Measured_current (void)
{
	return Amplitude;
};

//unsigned int Measured_current(void)
//{
//	return RMS;
//}

